package jdklearning.ref;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;


public class WeakRefLearning {

	
	public static void main(String[] args) {
		
		WeakRefLearning wrl = new WeakRefLearning();
		wrl.weak1();
	}

	
	/**
	 * 在上例中, 程序运行一段时间后, 程序打印出"Object has been collected." 说明, 
	 * weak reference指向的对象的被回收了.
		值得注意的一点 , 即使有 car 引用指向对象, 且 car 是一个strong reference, weak reference weakCar指向的对象仍然被回收了. 这是因为java的编译器在发现进入while循环之后
		, car 已经没有被使用了, 所以进行了优化(将其置空?). 当把TestWeakReference.java修改为:
	 */
	private void weak1() {
		Object o= new Object();
		
		ReferenceQueue<Object> rq = new ReferenceQueue<>();
		WeakReference<Object> weakObj = new WeakReference<Object>(o, rq);
		int i=0;
		while(true){
			if(weakObj.get()!=null){
				i++;
				System.out.println("Object is alive for "+i+" loops - "+weakObj);
			}else{
				System.out.println("Object has been collected.");
				break;
			}
		}
		
			try {
				System.out.println(rq.remove());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
	
	
	/**
	 * weak reference指向的object就不会被回收了. 因为还有一个strong reference car 指向它.
	 */
	private void weak2() {
		Object o= new Object();
		WeakReference<Object> weakObj = new WeakReference<Object>(o);
		int i=0;
		while(true){
			System.out.println("here is the strong reference 'o' " + o);
			if(weakObj.get()!=null){
				i++;
				System.out.println("Object is alive for "+i+" loops - "+weakObj);
			}else{
				System.out.println("Object has been collected.");
				break;
			}
		}
		
	}
}
